package com.example.studentvotesystem.service;

import com.example.studentvotesystem.entity.VoteRecord;
import com.example.studentvotesystem.mapper.VoteRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class VoteService {
    @Autowired
    private VoteRecordMapper voteRecordMapper;

    @Autowired
    private ScenicSpotService scenicSpotService;

    @Transactional
    public boolean vote(Integer userId, Integer spotId) {
        // 检查是否已经投过票
        VoteRecord existRecord = voteRecordMapper.selectByUserAndSpot(userId, spotId);
        if (existRecord != null) {
            return false;
        }

        // 插入投票记录
        VoteRecord voteRecord = new VoteRecord();
        voteRecord.setUserId(userId);
        voteRecord.setSpotId(spotId);
        voteRecordMapper.insert(voteRecord);

        return true;
    }

    public boolean hasVoted(Integer userId, Integer spotId) {
        return voteRecordMapper.selectByUserAndSpot(userId, spotId) != null;
    }

    public int getVoteCountBySpot(Integer spotId) {
        return voteRecordMapper.countBySpot(spotId);
    }

    public int getVoteCountByUser(Integer userId) {
        return voteRecordMapper.countByUser(userId);
    }
}
